package com.wy.cms.initconfig;

import com.wy.common.exception.BizException;
import com.wy.constant.ConfigConst;
import com.wy.domain.CmsResource;
import com.wy.protocol.ERRORCODE;
import com.wy.service.ex.ICmsResourceExService;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ResourceInitConfig {
	
	private static Element root = null;
	
	static{
		SAXReader sr = new SAXReader();
		try {
			InputStream in = ResourceInitConfig.class.getClassLoader().getResourceAsStream(ConfigConst.RESOURCE);
			Document doc = sr.read(in);
			root = doc.getRootElement();
			in.close();
			doc.clearContent();
		} catch (Exception e) {
			throw new BizException(ERRORCODE.FAIL.getCode(), ERRORCODE.FAIL.getMessage());
		}
	}
	
	public static void init() throws Exception{

		ResourceInitConfig resourceInitConfig = new ResourceInitConfig();
		resourceInitConfig.initResource();
	}

	@Autowired
	private ICmsResourceExService cmsResourceExService;

	private void initResource() throws Exception{
		cmsResourceExService.deleteAll();
		List<Element> resources = root.elements("resource");

		List<Element> resourceChilds = null;
		
		StringBuffer one_id = new StringBuffer();
		StringBuffer two_id = new StringBuffer();

		long currentTime = System.currentTimeMillis();

		List<CmsResource> cmsResources = new ArrayList<CmsResource>();

		CmsResource cmsResource = null;

		int i = 1;

		int parentId = 0;

		for(Element resource : resources){
			cmsResource = new CmsResource();
			cmsResource.setId(i);
			cmsResource.setCreateDate(currentTime);
			cmsResource.setName(resource.attributeValue("name"));
			cmsResource.setUrl(resource.attributeValue("url"));
			cmsResource.setParentId(0l);
			cmsResources.add(cmsResource);

			resourceChilds = resource.elements("resource");

			if(null!=resourceChilds&&resourceChilds.size()>0){

				parentId = i;
				for(Element resourceChild : resourceChilds){
					cmsResource = new CmsResource();
					cmsResource.setId((long)i);
					cmsResource.setCreateDate(currentTime);
					cmsResource.setName(resource.attributeValue("name"));
					cmsResource.setParentId((long)parentId);
					cmsResource.setUrl(resource.attributeValue("url"));
					cmsResources.add(cmsResource);
					i++;
				}
			}
			i++;
		}
		cmsResourceExService.batchInsert(cmsResources);

	}
}
